import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios'
import router from "../router";
import {layer} from "@layui/layui-vue";


type TAxiosOption = {
    timeout: number;
    baseURL: string;
}


const config = {
    timeout: 15000,
    baseURL: import.meta.env.BASE_URL
}
 
class Http {

    service;
    constructor(config: TAxiosOption) {
        this.service = axios.create(config)

        /* 请求拦截 */
        // @ts-ignore
        this.service.interceptors.request.use((config: AxiosRequestConfig) => {
            const token = localStorage.getItem('token');
            const cur_path = router.currentRoute.value.path;
            if (token !== null) {
                const token_info = JSON.parse(token);
                // console.log('token is ', token_info)
                if(token_info.token !== ''){
                    (config.headers as AxiosRequestHeaders).Authorization = 'Token ' + token_info.token;
                    (config.headers as AxiosRequestHeaders).userNo = token_info.userInfo.user_no;
                }else if ( cur_path === '/user/login') {
                    console.log('token is "", login page skip')
                }else if(cur_path === '/user/register') {
                    console.log('token is "", register page skip')
                }else {
                    router.push('/user/login');
                }
            } else {
                if(router.currentRoute.value.path==='/user/login') {
                    console.log('token is null, login page skip')
                }else if(router.currentRoute.value.path==='/user/register'){
                    console.log('token is null, register page skip')
                }else {
                    router.push('/user/login');
                }
            }
            return config
        }, error => {
            layer.msg('error:' + JSON.stringify(error), {icon: 2})
            return Promise.reject(error);
        })

        /* 响应拦截 */
        this.service.interceptors.response.use((response: AxiosResponse<any>) => {
            // const data = response.data
            // 错误处理 to do
            return response.data
        }, error => {
            let response = error.response;
            console.log('response error', response)
            if(response) {
                const status = response.status;
                console.log(status)
                if (status === 401) {
                    // 判断状态码是401 跳转到登录
                    router.push('/user/login');
                }else if(status === 400 || status === 404){
                    layer.closeAll();
                    layer.msg("请求响应失败！", { icon : 2, time: 3000});
                }else {
                    layer.msg("发生未知错误，请检查服务是否正常！", { icon : 2, time: 3000});
                }
            }else {
                layer.msg("发生未知错误，请检查服务是否正常！", { icon : 2, time: 3000});
            }
            return Promise.reject(error)
        })
    }

    /* GET 方法 */
    get(url: string, params?: object, _object = {}): Promise<any> {
        return this.service.get(url, { params, ..._object })
    }
    /* POST 方法 */
    post(url: string, params?: object, _object = {}): Promise<any> {
        return this.service.post(url, params, _object)
    }
    /* PUT 方法 */
    put(url: string, params?: object, _object = {}): Promise<any> {
        return this.service.put(url, params, _object)
    }
    /* DELETE 方法 */
    delete(url: string, params?: any, _object = {}): Promise<any> {
        return this.service.delete(url, { params, ..._object })
    }

    deleteMethod(url: string, params?: any): Promise<any> {
        return this.service.delete(url, { params })
    }
}

export default new Http(config)